<template>
	<div>
		
		<van-search @search="onSearch" @input="onInput" v-model="kw" placeholder="请输入搜索关键词" />
		
		<!-- 搜索提示 -->
		<div class="search-show" v-show="isShow">
			<div v-for="(item,index) in searchTs" @click="onSearchts(item.title)">
				<div style="padding: 10px 0;margin: 0 10px;">{{item.title}}</div>
			</div>
		</div>
		
		<!-- 搜索记录 -->
		
		<div v-show="!isShow">
			<div>搜索记录：</div>
			<div>
				<div v-for="(item,index) in searchList" style="margin: 10px 0;">
					<span>{{item}}</span>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	export default{
		data(){
			return{
				kw:'',
				isShow:false,
				list:[], //所有数据
				searchTs:[], //搜索提示
				searchList:JSON.parse(localStorage.getItem('searchList')) || [], //搜索记录
			}
		},
		mounted() {
			this.$axios.get('/search.json').then(res=>{
				console.log(res.data.data)
				this.list = res.data.data
			})
			
			if(this.kw.trim() == ''){
				this.isShow = false
			}
		},
		methods:{
			onSearchts(title){ //点击搜索提示
				this.isShow = false
				
				if(!this.searchList.includes(title)){ //不会重复添加相同搜索记录
					this.searchList.unshift(title)
				}
				
				this.kw = ''
				
				if(this.searchList.length > 4){
					this.searchList.pop()
				}
				
				localStorage.setItem('searchList',JSON.stringify(this.searchList))
			},
			onSearch(){ //确定搜索时触发
				this.isShow = false
				if(this.searchList.includes(this.kw.trim())){
					return
				}else{
					this.searchList.unshift(this.kw)
				}
				
				this.kw = ''
				if(this.searchList.length > 4){
					this.searchList.pop()
				}
				
				localStorage.setItem('searchList',JSON.stringify(this.searchList))
			},
			onInput(){
				this.searchTs = []
				this.list.forEach(item=>{
					if(item.title.includes(this.kw.trim())){
						this.searchTs.push(item)
					}
				})
				
				if(this.kw.trim() == ''){
					this.isShow = false
				}else{
					this.isShow = true
				}
			}
		}
	}
</script>

<style>
	.search-show{
		background-color: white;
		min-height: 300px;
		/* visibility: hidden; */
	}
	
</style>
